{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 局部变量\n",
    "from SubFunc import printID\n",
    "\n",
    "num = 1\n",
    "\n",
    "\n",
    "def test1():\n",
    "    num = 2  # 这个与上面的num不是同一个,这里重新新建了一个局部的num\n",
    "    printID(num)\n",
    "\n",
    "\n",
    "test1()\n",
    "printID(f\"{num}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 在局部作用域修改全局变量\n",
    "from SubFunc import printID\n",
    "\n",
    "num = 1\n",
    "printID(f\"test2: {num}\")\n",
    "\n",
    "\n",
    "def test2():\n",
    "    global num  # 这里会抓取外侧的num的值,并修改\n",
    "    num = 2  #\n",
    "    printID(f\"test2: {num}\")\n",
    "\n",
    "\n",
    "test2()\n",
    "printID(f\"test2: {num}\")  # 一般情况下ID不会被改变,但在Jupyter里面ID会被改变"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Lambda函数\n",
    "def plus1(a, b):\n",
    "    return a + b\n",
    "\n",
    "\n",
    "print(plus1(2, 3))\n",
    "\n",
    "\n",
    "plus2 = lambda a, b: a + b\n",
    "\n",
    "print(plus2(2, 3))\n",
    "\n",
    "# plus1 和 plus2 是等价的,可以代替def"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Use Lambda: [{'name': 'a', 'age': 4}, {'name': 'b', 'age': 2}, {'name': 'c', 'age': 3}, {'name': 'd', 'age': 1}]\n",
      "Use Lambda: [{'name': 'd', 'age': 1}, {'name': 'b', 'age': 2}, {'name': 'c', 'age': 3}, {'name': 'a', 'age': 4}]\n"
     ]
    }
   ],
   "source": [
    "# 通过将一个提取某个值作为判断依据的Lambda函数,让sorted函数进行排序\n",
    "exempleList = [\n",
    "    {\"name\": \"d\", \"age\": 1},\n",
    "    {\"name\": \"c\", \"age\": 3},\n",
    "    {\"name\": \"b\", \"age\": 2},\n",
    "    {\"name\": \"a\", \"age\": 4},\n",
    "]\n",
    "\n",
    "print(sorted(exempleList, key=lambda k: k[\"name\"]))\n",
    "print(sorted(exempleList, key=lambda k: k[\"age\"]))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
